import json

from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from redis import Redis

from apps.user.models import User
from django import http
import re


# 用户名重复
class UsernameCountView(View):
    def get(self, request, username):
        """
        :param request: 请求对象
        :param username: 用户名
        :return: JSON
        """
        # 1.接收用户名
        print(username)
        try:
            # 2.根据用户名查询数据库，查询数量有几个
            count = User.objects.filter(username=username).count()
        except Exception as e:
            print(e)
            return JsonResponse({'count': '15', 'errmag': 'OK'})
        print('count=', count)
        # 3.返回json数据
        return JsonResponse({'count': count, 'code': '0', 'errmag': 'OK'})


# 手机号重复
class MobileCountView(View):
    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """
        print(mobile)
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            print(e)
            return JsonResponse({'count': '15', 'errmag': 'OK'})
        print('count=', count)
        return JsonResponse({'count': count, 'code': '0', 'errmag': 'OK'})


# 用户注册
class RegisterView(View):
    def post(self, request):
        body_byte = request.body
        data_dict = json.loads(body_byte)
        print(data_dict)
        username = data_dict.get('username')
        print(username)
        password = data_dict.get('password')
        print(password)
        password2 = data_dict.get('password2')
        print(password2)
        mobile = data_dict.get('mobile')
        print(mobile)
        allow = data_dict.get('allow')
        sms_code = data_dict.get('sms_code')
        if not all([username, password, password2, mobile, allow]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数!'})
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '注册失败!'})
        login(request, user)

        # 判断短信验证是否正确
        # 1. 从redis取短信验证码 不要忘记decode
        redis: Redis = get_redis_connection('code')
        sms_code_redis = redis.get('smscode_%s' % mobile)
        # 2.如果没取到说明过期 ，返回错误
        if not sms_code_redis:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'})
        # 3.和用户发来的对比
        sms_code_redis = sms_code_redis.decode()
        if sms_code != sms_code_redis:
            return JsonResponse({'code': 400, 'errmsg': '验证码过期'})

        return http.JsonResponse({'code': 0, 'errmsg': '注册成功!'})
